<template>
  <view class="search-page">
    <UAMHeader :title="title" />
    
    <!-- 搜索区域 -->
    <uni-section title="搜索" type="line">
      <uni-search-bar 
        v-model="searchValue"
        :focus="true"
        @confirm="handleSearch"
        @blur="handleBlur"
        @focus="handleFocus"
        @clear="handleClear"
        @input="onInput"
      />
    </uni-section>

    <!-- 搜索建议 -->
    <transition name="fade">
      <view class="search-suggestion" v-if="showSuggestions && hasSuggestions && !showSearchResults">
        <view class="suggest-section" v-if="suggestList.songs?.length">
          <view 
            class="suggest-item" 
            v-for="item in suggestList.songs" 
            :key="item.id" 
            @click="selectSuggestion(item)"
          >
            <text class="suggest-key">{{ item.name }}</text>
            <text class="suggest-hint">{{ item.artists?.map(a => a.name).join('/') || '未知艺术家' }}</text>
          </view>
        </view>
      </view>
    </transition>

    <!-- 搜索历史 -->
    <uni-section title="搜索历史" type="line" v-if="searchHistory.length">
      <view class="history-container">
        <view class="history-tags">
          <view 
            class="history-tag" 
            v-for="(item, index) in searchHistory" 
            :key="index" 
            @click="useHistory(item)"
          >
            {{ item }}
            <text class="iconfont icon-shanchu" @click.stop="deleteHistory(index)" />
          </view>
        </view>
        <view class="clear-all" @click="clearAllHistory">清空历史</view>
      </view>
    </uni-section>
    
    <!-- 热搜榜 -->
    <uni-section title="热搜榜" type="line" v-if="!showSearchResults && !searchValue">
      <view class="hot-container">
        <view 
          class="hot-tag" 
          v-for="(item, index) in hotList" 
          :key="item.searchWord"
          @click="useHotKeyword(item.searchWord)"
        >
          <text :class="['hot-rank', index < 3 ? 'top-three' : '']">{{ index + 1 }}</text>
          <view class="hot-info">
            <text class="hot-word">{{ item.searchWord }}</text>
            <text v-if="item.iconType === 1" class="hot-hot">HOT</text>
            <text v-if="item.content" class="hot-sub">{{ item.content }}</text>
          </view>
          <text class="hot-count">{{ formatNumber(item.score) }}</text>
        </view>
      </view>
    </uni-section>
    
    <!-- 搜索结果 -->
    <transition name="fade">
      <uni-section title="搜索结果" type="line" v-if="showSearchResults">
        <view class="search-results-container">
          <view v-if="isLoading" class="loading">加载中...</view>
          <view v-else-if="!searchResults.length" class="empty-result">没有找到相关结果</view>
          <view v-else>
            <view 
              class="result-item" 
              v-for="item in searchResults" 
              :key="item.id" 
              @click="playSong(item)"
            >
              <view class="result-info">
                <text class="result-title">{{ item.name }}</text>
                <text class="result-artist">{{ item.artists?.map(a => a.name).join('/') || '未知艺术家' }}</text>
                <text class="result-album">{{ item.album?.name || '未知专辑' }}</text>
              </view>
              <text class="iconfont icon-bofang1 play-icon" />
            </view>
          </view>
        </view>
      </uni-section>
    </transition>
  </view>
</template>

<script>
import { searhHotDetail, searchSuggest, searchWord } from '@/common/api.js';

export default {
  data() {
    return {
      title: '搜索',
      searchValue: '',
      searchHistory: [],
      hotList: [],
      suggestList: { songs: [], artists: [], albums: [], playlists: [] },
      showSuggestions: false,
      showSearchResults: false,
      searchResults: [],
      isLoading: false
    };
  },

  computed: {
    hasSuggestions() {
      return Object.values(this.suggestList).some(list => list?.length > 0);
    }
  },

  onLoad() {
    this.loadSearchHistory();
    this.getHotSongs();
  },

  methods: {
    async getHotSongs() {
      try {
        const { data } = await searhHotDetail();
        if (data.code === 200 && data.data) {
          this.hotList = data.data.slice(0, 10);
        }
      } catch (error) {
        console.error('获取热门歌曲失败:', error);
      }
    },

    async handleSearch() {
      const keyword = this.searchValue.trim();
      if (!keyword) {
        uni.showToast({ title: '请输入搜索内容', icon: 'none' });
        return;
      }
      
      this.saveSearchHistory(keyword);
      this.showSuggestions = false;
      this.showSearchResults = true;
      this.isLoading = true;

      try {
        const { data } = await searchWord(keyword);
        this.searchResults = data.code === 200 && data.result?.songs ? data.result.songs : [];
      } catch (error) {
        console.error('搜索失败:', error);
        uni.showToast({ title: '搜索失败，请重试', icon: 'none' });
        this.searchResults = [];
      } finally {
        this.isLoading = false;
      }
    },

    async getSuggestions(keyword) {
      if (!keyword) {
        this.resetSuggestions();
        return;
      }
      
      try {
        const { data } = await searchSuggest(keyword);
        if (data?.code === 200 && data?.result) {
          this.suggestList = {
            songs: data.result.songs || [],
            artists: data.result.artists || [],
            albums: data.result.albums || [],
            playlists: data.result.playlists || []
          };
          this.showSuggestions = this.hasSuggestions;
        } else {
          this.resetSuggestions();
        }
      } catch (error) {
        console.error('获取搜索建议失败:', error);
        this.resetSuggestions();
      }
    },

    resetSuggestions() {
      this.suggestList = { songs: [], artists: [], albums: [], playlists: [] };
      this.showSuggestions = false;
    },

    selectSuggestion(item) {
      if (item?.name) {
        this.searchValue = item.name;
        this.handleSearch();
      }
    },

    useHotKeyword(keyword) {
      this.searchValue = keyword;
      this.handleSearch();
    },

    saveSearchHistory(keyword) {
      const index = this.searchHistory.indexOf(keyword);
      if (index !== -1) this.searchHistory.splice(index, 1);
      this.searchHistory.unshift(keyword);
      if (this.searchHistory.length > 10) this.searchHistory.pop();
      uni.setStorageSync('searchHistory', this.searchHistory);
    },

    loadSearchHistory() {
      const history = uni.getStorageSync('searchHistory');
      if (history) this.searchHistory = history;
    },

    useHistory(keyword) {
      this.searchValue = keyword;
      this.showSuggestions = false;
      this.showSearchResults = true;
      this.handleSearch();
    },

    deleteHistory(index) {
      this.searchHistory.splice(index, 1);
      uni.setStorageSync('searchHistory', this.searchHistory);
    },

    clearAllHistory() {
      uni.showModal({
        title: '提示',
        content: '确定要清空搜索历史吗？',
        success: (res) => {
          if (res.confirm) {
            this.searchHistory = [];
            uni.removeStorageSync('searchHistory');
            uni.showToast({ title: '历史记录已清空', icon: 'none' });
          }
        }
      });
    },

    formatNumber(num) {
      if (num >= 1000000000) return (num / 1000000000).toFixed(1) + 'B';
      if (num >= 1000000) return (num / 1000000).toFixed(1) + 'M';
      if (num >= 1000) return (num / 1000).toFixed(1) + 'K';
      return num.toString();
    },

    handleBlur() {
      uni.hideKeyboard();
      setTimeout(() => this.showSuggestions = false, 200);
    },

    handleFocus() {
      setTimeout(() => {
        this.loadSearchHistory();
        if (this.searchValue.trim() && !this.showSearchResults) {
          this.getSuggestions(this.searchValue.trim());
        }
      }, 100);
    },

    handleClear() {
      this.searchValue = '';
      this.showSuggestions = false;
      this.showSearchResults = false;
      this.resetSuggestions();
    },

    onInput(e) {
      const value = typeof e === 'string' ? e : (e?.detail?.value ?? '');
      this.getSuggestions(value);
      if (!value) this.showSearchResults = false;
    },

    playSong(item) {
      if (!item?.id) {
        uni.showToast({ title: '无效的歌曲信息', icon: 'none' });
        return;
      }
      uni.navigateTo({ url: `/pages/player/player?id=${item.id}` });
    }
  }
};
</script>

<style lang="scss">
.search-page {
  min-height: 100vh;
  background: #f8f8f8;
}

// 搜索栏样式
uni-search-bar {
  --uni-search-bar-bg-color: #fff;
  --uni-search-bar-input-padding: 16rpx 24rpx;
  --uni-search-bar-input-font-size: 28rpx;
  --uni-search-bar-cancel-color: #d43c33;
}

// 搜索建议样式
.search-suggestion {
  margin: 10rpx 20rpx;
  background: #fff;
  border-radius: 12rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);
  overflow: hidden;
}

.suggest-item {
  padding: 20rpx 24rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1rpx solid #f5f5f5;
  transition: background-color 0.3s;

  &:active {
    background-color: #f8f8f8;
  }

  &:last-child {
    border-bottom: none;
  }
}

.suggest-key {
  font-size: 28rpx;
  color: #333;
}

.suggest-hint {
  font-size: 24rpx;
  color: #999;
}

// 热搜榜样式
.hot-container {
  padding: 20rpx;
}

.hot-tag {
  display: flex;
  align-items: center;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
  transition: background-color 0.3s;

  &:active {
    background-color: #f8f8f8;
  }

  &:last-child {
    border-bottom: none;
  }
}

.hot-rank {
  width: 40rpx;
  text-align: center;
  font-size: 32rpx;
  font-weight: bold;
  margin-right: 16rpx;
  color: #bbb;

  &.top-three {
    color: #d43c33;
  }
}

.hot-info {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.hot-word {
  font-weight: bold;
  font-size: 30rpx;
}

.hot-hot {
  color: #d43c33;
  font-style: italic;
  font-size: 24rpx;
  margin-left: 8rpx;
}

.hot-sub {
  color: #aaa;
  font-size: 22rpx;
  margin-top: 2rpx;
}

.hot-count {
  font-size: 24rpx;
  color: #e0e0e0;
  margin-left: 16rpx;
}

// 搜索历史样式
.history-container {
  padding: 20rpx;
}

.history-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 12rpx;
  padding: 16rpx 0;
}

.history-tag {
  display: flex;
  align-items: center;
  background: #fff;
  border-radius: 24rpx;
  padding: 12rpx 20rpx;
  font-size: 24rpx;
  color: #333;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
  transition: all 0.3s;

  &:active {
    transform: scale(0.98);
  }
}

.clear-all {
  text-align: center;
  padding: 20rpx 0;
  font-size: 24rpx;
  color: #999;
  border-top: 1rpx solid #f0f0f0;
}

// 搜索结果样式
.search-results-container {
  padding: 10rpx 0;
}

.loading, .empty-result {
  text-align: center;
  padding: 40rpx 0;
  color: #999;
}

.result-item {
  display: flex;
  align-items: center;
  padding: 20rpx;
  border-bottom: 1rpx solid #f0f0f0;
  transition: background-color 0.3s;

  &:active {
    background-color: #f8f8f8;
  }

  &:last-child {
    border-bottom: none;
  }
}

.result-info {
  flex: 1;
  min-width: 0;
}

.result-title {
  display: block;
  font-size: 28rpx;
  color: #333;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.result-artist {
  display: block;
  font-size: 24rpx;
  color: #666;
  margin-top: 4rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.result-album {
  display: block;
  font-size: 22rpx;
  color: #999;
  margin-top: 2rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.play-icon {
  font-size: 40rpx;
  color: #999;
  margin-left: 20rpx;
}

// 动画
.fade-enter-active, .fade-leave-active {
  transition: opacity 0.3s;
}

.fade-enter, .fade-leave-to {
  opacity: 0;
}

// 公共样式
.uni-section {
  margin-bottom: 20rpx;
  background: #fff;
  border-radius: 12rpx;
  overflow: hidden;
}

.icon-shanchu:before {
  content: "\e7ea";
}
</style>